﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Threading.Tasks;

namespace SharpShare.Diagnostics {
    public static class Log {
        public delegate void EntryAddedHandler(LogEntry entry);

        public static event EntryAddedHandler EntryAdded;

        public static void Add(object sender, EntryType type, string message, params object[] formatParams) {
            Add(sender, type, Verbosity.Low, message, formatParams);
        }
        public static void Add(object sender, EntryType type, Verbosity verbosity, string message, params object[] formatParams) {
            Add(new LogEntry() {
                Sender = sender,
                Type = type,
                Message = string.Format(message, formatParams),
                Verbosity = verbosity,
                Exception = null
            });
        }
        public static void Add(LogEntry entry) {
            OnEntryAdded(entry);
        }

        private static void OnEntryAdded(LogEntry entry) {
            Task.Factory.StartNew(() => {
                try {
                    if (EntryAdded != null)
                        EntryAdded(entry);
                } catch { }

                if (entry.Type != EntryType.Debug) {
                    try {
                        lock (_writeLock) {
                            if (_htmlWriter != null) {
                                entry.WriteHtml(_htmlWriter);
                            }
                        }
                    } catch { }
                }
            });
        }

        private static object _writeLock = new object();
        private static StreamWriter _htmlWriter;

        public static StreamWriter HtmlWriter {
            set {
                lock (_writeLock) {
                    if (_htmlWriter != null) {
                        _htmlWriter.Write("</body></html>");
                        _htmlWriter.Flush();
                    }

                    _htmlWriter = value;

                    if (_htmlWriter != null) {
                        _htmlWriter.AutoFlush = true;
                        _htmlWriter.Write("<html><head><title>SharpShare Log {0}</title><style>{1}</style><META HTTP-EQUIV=\"CACHE-CONTROL\" CONTENT=\"NO-CACHE\"><!--<meta http-equiv=\"refresh\" content=\"1\">--></head><!--<body onload=\"window.scroll(0, 10000000);\">--><body>",
                            DateTime.Now, "body { font: 12pt 'Courier New'; white-space:nowrap; }");
                    }
                }
            }
            get {
                lock (_writeLock) {
                    return _htmlWriter;
                }
            }
        }
    }
}
